MongoDB foreach Example – cursor.forEach() method & Traverse Usage 您所在的位置:网站首页 mongo foreach MongoDB foreach Example – cursor.forEach() method & Traverse Usage

MongoDB foreach Example – cursor.forEach() method & Traverse Usage

2023-04-11 05:09| 来源: 网络整理| 查看: 265

Introduction

This article focuses on the MongoDB forEach Example and traversal usage. MongoDB forEach function looping operators is a very common function that you should know if you deal with the database.

If you have the MongoDB application installed on Windows or Ubuntu, and you want to learn the cursor.forEach() method, follow the steps below. The method is very simple.

How to use Node.js with a cursor.forEach() in MongoDB?

The answer of this question depends on the driver you are using. I know that there is one way or another for all MongoDB drivers to implement cursor.forEach ().

Here are some examples:

node-mongodb-native 123collection.find(query).each(function(err, doc) {   // handle }); Mongojs 123db.collection.find(query).forEach(function(err, doc) {   // handle }); Monk 12345678910collection.find(query, { stream: true })   .each(function(doc){     // handle doc   })   .error(function(err){     // handle error   })   .success(function(){     // final callback   }); Mongoose 12345678910collection.find(query).stream()   .on('data', function(doc){     // handle doc   })   .on('error', function(err){     // handle error   })   .on('end', function(){     // final callback   });

Update the document in the .forEach callback.

The only problem with updating the files in the .forEach callback is that you don’t know if all the documents have been updated.

To solve this problem, you must use some solutions to the asynchronous control process. Here are a few options:

asynchronous Commitment (when .js, bluebird)

Here is an example of using asynchronously using the queue function:

1234567891011121314151617181920212223var q = async.queue(function (doc, callback) {   // code for your update   collection.update({     _id: doc._id   }, {     $set: {hi: 'there'}   }, {     w: 1   }, callback); }, Infinity); var cursor = collection.find(query); cursor.each(function(err, doc) {   if (err) throw err;   if (doc) q.push(doc); // dispatching doc to async.queue }); q.drain = function() {   if (cursor.isClosed()) {     console.log('all items have been processed');     db.close();   } } MongoDB ForEach Example of multiple tables joins operation 1234567891011121314151617181920212223242526272829303132333435363738394041424344//You can also call the function var param = db.sm_pm_paramconfig.find({         paramGroup: "BUSINESSUNIT" 
    }); //Traversing the information table db.userinfo.find().forEach(function(item) {     var arr = item.address.split("_"); //Get department name var deptName = "";     var num = -1;     for (var i = 0; i = 0) {         deptName = arr[num + 1];     } else {         deptName = "****";     } //Insert ID //Note: The object obtained by param must be toarray to traverse. var config = param.toArray();     for (var j = 0, len = config.length; j var arr = ["ab","cd","ef"] >var show = function(value,index,ar){ print(value) } >arr.forEach(show) ab cd ef Additional – Browser-Side forEach Example

Let’s look at how forEach is similarly used in Javascript in the browser:

12345678910111213//value is the current element value, index is the index of the current element in the array, ar is the array itself functionShowResults(value, index, ar) { document.write("value:" + value); document.write("index: " + index); document.write("name: " + this.name); document.write(" "); } varletters = ['ab', 'cd', 'ef']; varscope = { name: 'scope' }; // ShowResults is a callback function, the scope sets the context for the callback, so this callback function points to the scope variable, and the scope is an optional parameter. letters.forEach(ShowResults,scope); Mongodb uses foreach query and cursor traversal

The find method uses the cursor to return the result of the query, and the client implementation of the cursor gives you full control over the final result. Creating a cursor in a shell is very simple. First you have to put some documents into the collection.

Run the query and assign the returned result to a local variable.

1234> var cursor = db.collection.find(); > while (cursor.hasNext()) {    obj = cursor.next();    }

The cursor class also implements the iterator interface, so you can use a forEach loop.

1234> var cursor = db.people.find(); > cursor.forEach( function (x) {   ... print(x.name);   ... }); 12345678910111213141516db.Goods.find().forEach(     function(item){         if(!item.goodsCode.indexOf("ABCD")){                 var tempGoodId=item._id;                 var tempGoodCode=item.goodsCode;                 var temp=db.Goods.findOne({"goodsCode":{"$regex":"^"+tempGoodCode+".+"}});                 if(temp){                     // print(tempGoodCode+"="+item._id);                     var cursor=db.GoodAttr.find({"goodsId":tempGoodId});                      cursor.forEach(function(a){                         print(a);                               })                     }                           }         }     ) MongoDB array traversal operation forEach

The seq type in the following collection is double and you want to change it to int.

12345678910111213141516171819202122{     "_id" : ObjectId("592e94fee820cc1813f0b9a2"),     "privateAttrs" : [         {             "attrId" : "100",             "seq" : 0         },         {             "attrId" : "101",             "seq" : 1         }     ] } {     "_id" : ObjectId("592e94fee820cc1813f0b9a3"),     "privateAttrs" : [         {             "attrId" : "102",             "seq" : 0         }     ] } Traversing the array through forEach: 12345678910db.category.find().forEach(     function(item) {         item.privateAttrs.forEach(             function(arr, index) {                 item.privateAttrs[index].seq = new NumberInt(item.privateAttrs[index].seq);             }         );         db.category.save(item);     } )

The callback function in the forEach method has three parameters: the first parameter is the contents of the array traversed, the second parameter is the corresponding array index, and the 3rd parameter is the array itself.

Conclusion

We have showed you several examples of how to use forEach and cursors with MongoDB and we hope you can apply what you’ve learned to your application. If you’re working with MongoDB and need someone to manage your database security, backups, or performance please don’t hesitate to reach out to us at Object Rocket.



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有